/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2009-11 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus.parser;

import org.pz.platypus.GDD;
import org.pz.platypus.exceptions.StopExecutionException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Parses an input file and returns a TokenList of all the constituent Platypus tokens
 * @author alb
 */
public class FileParser
{
    private String filename;
    private GDD gdd;

    FileParser( final String filepath, GDD Gdd )
    {
        filename = checkNotNull( filepath );
        gdd = checkNotNull( Gdd );
    }

    public TokenList parse()
    {
        return( parse( new ParserState() ));
    }

    public TokenList parse( final ParserState parserState )
    {
        TokenList fileTokens = new TokenList();
        TokenList lineTokens;
        LineParser lineParser = new LineParser();
        int lineCount = 0;

        try{
            BufferedReader infile = new BufferedReader( new FileReader( checkNotNull( filename )));
            String line;
            while(( line = infile.readLine()) != null ) {
                InputLine inputLine = new InputLine( 0, ++lineCount, line );
                lineTokens = lineParser.parseLine( inputLine, parserState, gdd );
                fileTokens.addAll( lineTokens );
            }
        }
        catch( IOException ioe ) {
            gdd.log.severe( gdd.getLit( "ERROR.READING_PLATYPUS_FILE" + " " + filename +
                            gdd.getLit( "EXISTING" )));
            throw new StopExecutionException( null );
        }

        return( fileTokens );
    }
}
